#include "servertcp.h"
#include <QDebug>
#include "databasehandler.h"

ServerTcp::ServerTcp(QObject *parent)
    : QTcpServer(parent), socket(nullptr) // 初始化socket为nullptr
{
}

ServerTcp::ServerTcp(qint16 port,const QString &host,QObject *parent)
    : QTcpServer(parent), socket(nullptr) // 初始化socket为nullptr
{
    this->port = port; // 设置服务器端口
    if (!this->listen(QHostAddress::Any, port)) {
        qFatal("Failed to start the server."); // 服务器启动失败时打印错误信息
    }
    qDebug() << "Server started on port" << port; // 打印服务器启动信息

    // 连接新连接信号到槽函数
    connect(this, &QTcpServer::newConnection, this, &ServerTcp::onNewConnection);

    /*************************************************************************************/
    m_server = new QTcpServer(this);
       connect(m_server, &QTcpServer::newConnection, this, &ServerTcp::onNewConnection_2);

       if (!m_server->listen(QHostAddress::Any, 8899)) {
           qDebug() << "Server could not start!";
       } else {
           qDebug() << "Server started!";
       }
}

void ServerTcp::onNewConnection_2()
{
    QTcpSocket *clientSocket = m_server->nextPendingConnection();
    connect(clientSocket, &QTcpSocket::readyRead, this, &ServerTcp::onReadyRead);
    connect(clientSocket, &QTcpSocket::disconnected, this, &ServerTcp::onDisconnected);

    m_clients[clientSocket] = "Unknown";
    qDebug() << "New client connected:" << clientSocket->peerAddress().toString();
}

void ServerTcp::onReadyRead()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    if (!clientSocket)
        return;

    QByteArray data = clientSocket->readAll();
    qDebug() << "Received data:" << data;

    // Broadcast the message to all clients
    for (auto it = m_clients.begin(); it != m_clients.end(); ++it) {
        if (it.key() != clientSocket) {
            it.key()->write(data);
        }
    }
}

void ServerTcp::onDisconnected()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    if (!clientSocket)
        return;

    qDebug() << "Client disconnected:" << clientSocket->peerAddress().toString();
    m_clients.remove(clientSocket);
    clientSocket->deleteLater();
}
/***************************************************************************************/
void ServerTcp::onNewConnection() {
    // 获取下一个连接的套接字
    socket = this->nextPendingConnection();

    // 获取通信套接字的控制信息
    QString ip = socket->peerAddress().toString(); // 获取连接的 IP 地址
    quint16 port = socket->peerPort(); // 获取连接的端口号
    QString temp = QString("[%1:%2] 客户端连接成功").arg(ip).arg(port);
    qDebug() << temp;
    qDebug() << "==================================";

    // 根据端口号选择绑定的处理函数
    switch (this->port) {
    case USERS_DATA:
        connect(socket, &QTcpSocket::readyRead, this, &ServerTcp::onReadMsg_ReturnUsers);
        break;
    case DOCTORS_DATA:
        connect(socket, &QTcpSocket::readyRead, this, &ServerTcp::onReadMsg_ReturnDoctors);
        break;
    case PATIENTS_DATA:
        connect(socket, &QTcpSocket::readyRead, this, &ServerTcp::onReadMsg_ReturnPatients);
        break;
    case MEDICAL_RECORDS_DATA:
        connect(socket, &QTcpSocket::readyRead, this, &ServerTcp::onReadMsg_ReturnMedicalRecords);
        break;
    case APPOINTMENTS_DATA:
        connect(socket, &QTcpSocket::readyRead, this, &ServerTcp::onReadMsg_ReturnAppointments);
        break;
    case APPOINTMENTS_DATA_2:
        connect(socket, &QTcpSocket::readyRead, this, &ServerTcp::onReadMsg_ReturnAppointments_2);
        break;
    case MEDICAL_ADVICE_DATA:
        connect(socket, &QTcpSocket::readyRead, this, &ServerTcp::onReadMsg_ReturnMedicalAdvice);
        break;
    case PRESCRIPTIONS_DATA:
        connect(socket, &QTcpSocket::readyRead, this, &ServerTcp::onReadMsg_ReturnPrescriptions);
        break;
    case COMMUNICATION_DATA:
        connect(socket, &QTcpSocket::readyRead, this, &ServerTcp::onReadMsg_ReturnCommunication);
        break;
    case HEALTH_ASSESSMENTS_DATA:
        connect(socket, &QTcpSocket::readyRead, this, &ServerTcp::onReadMsg_ReturnHealthAssessments);
        break;
    case INSERT_DATA:
        connect(socket, &QTcpSocket::readyRead, this, &ServerTcp::onInsertData);
        break;
    case DEPARTMENTS_DATA:
        connect(socket, &QTcpSocket::readyRead, this, &ServerTcp::onReadMsg_ReturnDepartments);
        break;

    default:
        qDebug() << "Unknown port:" << port; // 未知端口处理
        break;
    }

    // 处理断开连接信号
    connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater);
}

// 发送消息到客户端
void ServerTcp::sendMsg(const QString &str) {
    if (socket) {
        socket->write(str.toUtf8());
        socket->flush(); // 确保数据被发送
    }
}

// 处理用户数据请求
void ServerTcp::onReadMsg_ReturnUsers() {
    QByteArray data = socket->readAll(); // 读取所有可用数据
    sql = QString::fromUtf8(data); // 转换为 QString
    qDebug() << "Received data:" << data; // 打印接收到的数据
    sendUsersData(); // 发送用户数据
}
// 处理用户数据请求
void ServerTcp::onInsertData() {
    QByteArray data = socket->readAll(); // 读取所有可用数据
    QString sql = QString::fromUtf8(data); // 转换为 QString
    qDebug() << "Received data:" << sql; // 打印接收到的数据
    sql = sql.trimmed(); // 去掉 SQL 末尾的空格
    qDebug() << "Executing SQL:" << sql;

    DatabaseHandler db;
    if (!db.connectToDatabase(DATABASE_PATH)) {
        qDebug() << "Failed to connect to database"; // 数据库连接失败处理
        sendMsg("Database connection failed");
        return;
    }

    QSqlQuery query;
    //    query.prepare(sql); // 准备 SQL 查询

    if (query.exec(sql)) {
        sendMsg("Successful"); // 发送成功消息
        qDebug() << "Insert successful"; // 发送成功消息
    } else {
        qDebug() << "Insert failed:" << query.lastError().text(); // 打印错误信息
        sendMsg("Insert failed: " + query.lastError().text()); // 发送失败消息，包含错误信息
    }
}


// 处理部门数据请求
void ServerTcp::onReadMsg_ReturnDepartments() {
    QByteArray data = socket->readAll(); // 读取所有可用数据
    sql = QString::fromUtf8(data); // 转换为 QString
    qDebug() << "Received data:" << data; // 打印接收到的数据
    sendDepartmentsData(); // 发送部门数据
}

// 发送部门数据
void ServerTcp::sendDepartmentsData() {
    jsonArray = QJsonArray(); // 清空 JSON 数组
    sql = sql.trimmed(); // 去掉 SQL 末尾的空格
    qDebug() << "Executing SQL:" << sql;

    DatabaseHandler db;
    if (!db.connectToDatabase(DATABASE_PATH)) {
        qDebug() << "Failed to connect to database"; // 数据库连接失败处理
        return;
    }

    QSqlQuery query;
    query.prepare(sql); // 准备 SQL 查询

    bool flag = false;
    if (query.exec()) { // 执行查询
        while (query.next()) {
            QJsonObject jsonData; // 创建 JSON 对象
            // 假设 Departments 表中的字段顺序
            jsonData["DepartmentID"] = query.value(0).toInt();
            jsonData["DepartmentName"] = query.value(1).toString();
            jsonData["Description"] = query.value(2).toString();

            jsonArray.append(jsonData); // 将 JSON 对象添加到数组

            flag = true;
        }
        if (flag) {
            QJsonDocument jsonDoc(jsonArray); // 创建 JSON 文档
            jsonString = jsonDoc.toJson(); // 转换为 JSON 字符串
            qDebug() << "Sending JSON:" << jsonString; // 打印发送的 JSON

            sendMsg(jsonString); // 发送消息
        } else {
            qDebug() << "No search return 'failed'";
            QString str = "failed";
            sendMsg(str);
        }
    } else {
        qDebug() << "Query execution failed:" << query.lastError().text(); // 查询失败处理
    }
}


// 发送用户数据
void ServerTcp::sendUsersData() {
    jsonArray = QJsonArray(); // 清空 JSON 数组
    sql = sql.trimmed(); // 去掉 SQL 末尾的空格
    qDebug() << "Executing SQL:" << sql;

    DatabaseHandler db;
    if (!db.connectToDatabase(DATABASE_PATH)) {
        qDebug() << "Failed to connect to database"; // 数据库连接失败处理
        return;
    }

    QSqlQuery query;
    query.prepare(sql); // 准备 SQL 查询

    bool flag = false;
    if (query.exec()) { // 执行查询
        while (query.next()) {

            QJsonObject jsonData; // 创建 JSON 对象
            // 假设 Users 表中的字段顺序
            jsonData["UserID"] = query.value(0).toInt();
            jsonData["Username"] = query.value(1).toString();
            jsonData["Password"] = query.value(2).toString();
            jsonData["Role"] = query.value(3).toString();
            jsonData["Name"] = query.value(4).toString();
            jsonData["Gender"] = query.value(5).toString();
            jsonData["Age"] = query.value(6).toInt();
            jsonData["ContactNumber"] = query.value(7).toString();
            jsonData["Email"] = query.value(8).toString();

            jsonArray.append(jsonData); // 将 JSON 对象添加到数组

            flag = true;
        }
        if(flag) {
            QJsonDocument jsonDoc(jsonArray); // 创建 JSON 文档
            jsonString = jsonDoc.toJson(); // 转换为 JSON 字符串
            qDebug() << "Sending JSON:" << jsonString; // 打印发送的 JSON

            sendMsg(jsonString); // 发送消息
        } else {
            qDebug() << "No search return 'failed'";
            QString str = "failed";
            sendMsg(str);
        }
    } else {
        qDebug() << "Query execution failed:" << query.lastError().text(); // 查询失败处理
    }
}

// 处理医生数据请求
void ServerTcp::onReadMsg_ReturnDoctors() {
    QByteArray data = socket->readAll();
    sql = QString::fromUtf8(data);
    qDebug() << "Received data:" << data;
    sendDoctorsData(); // 发送医生数据
}

// 发送医生数据
// 发送医生数据
void ServerTcp::sendDoctorsData() {
    jsonArray = QJsonArray();
    sql = sql.trimmed();
    qDebug() << "Executing SQL:" << sql;

    DatabaseHandler db;
    if (!db.connectToDatabase(DATABASE_PATH)) {
        qDebug() << "Failed to connect to database";
        return;
    }

    QSqlQuery query;
    query.prepare(sql);

    if (query.exec()) {
        while (query.next()) {
            QJsonObject jsonData;
            jsonData["DoctorID"] = query.value(0).toInt();           // DoctorID 是第0列
            jsonData["Name"] = query.value(1).toString();            // Name 是第1列
            jsonData["ContactNumber"] = query.value(2).toString();   // ContactNumber 是第2列
            jsonData["Specialization"] = query.value(3).toString();  // Specialization 是第3列
            jsonData["Experience"] = query.value(4).toInt();         // Experience 是第4列
            jsonData["Department"] = query.value(5).toString();      // Department 是第5列
            jsonData["Title"] = query.value(6).toString();           // Title 是第6列
            jsonData["Introduction"] = query.value(7).toString();    // Introduction 是第7列
            jsonData["AvatarPath"] = query.value(8).toString();      // AvatarPath 是第8列
             jsonData["Username"] = query.value(9).toString();
              jsonData["Password"] = query.value(10).toString();
               jsonData["Role"] = query.value(11).toString();
            jsonArray.append(jsonData);
        }

        QJsonDocument jsonDoc(jsonArray);
        jsonString = jsonDoc.toJson();
        qDebug() << "Sending JSON:" << jsonString;
        sendMsg(jsonString);
    } else {
        qDebug() << "Query execution failed:" << query.lastError().text();
    }
}



// 处理患者数据请求
void ServerTcp::onReadMsg_ReturnPatients() {
    QByteArray data = socket->readAll();
    sql = QString::fromUtf8(data);
    qDebug() << "Received data:" << data;
    sendPatientsData(); // 发送患者数据
}

// 发送患者数据
void ServerTcp::sendPatientsData() {
    jsonArray = QJsonArray();
    sql = sql.trimmed();
    qDebug() << "Executing SQL:" << sql;

    DatabaseHandler db;
    if (!db.connectToDatabase(DATABASE_PATH)) {
        qDebug() << "Failed to connect to database";
        return;
    }

    QSqlQuery query;
    query.prepare(sql);

    if (query.exec()) {
        while (query.next()) {
            QJsonObject jsonData;
            jsonData["PatientID"] = query.value(0).toInt();
            jsonData["MedicalHistory"] = query.value(1).toString();
            jsonData["Allergies"] = query.value(2).toString();

            jsonArray.append(jsonData);
        }

        QJsonDocument jsonDoc(jsonArray);
        jsonString = jsonDoc.toJson();
        qDebug() << "Sending JSON:" << jsonString;
        sendMsg(jsonString);
    } else {
        qDebug() << "Query execution failed:" << query.lastError().text();
    }
}

// 处理医疗记录请求
void ServerTcp::onReadMsg_ReturnMedicalRecords() {
    QByteArray data = socket->readAll();
    sql = QString::fromUtf8(data);
    qDebug() << "Received data:" << data;
    sendMedicalRecordsData(); // 发送医疗记录数据
}

// 发送医疗记录数据
void ServerTcp::sendMedicalRecordsData() {
    jsonArray = QJsonArray();
    sql = sql.trimmed();
    qDebug() << "Executing SQL:" << sql;

    DatabaseHandler db;
    if (!db.connectToDatabase(DATABASE_PATH)) {
        qDebug() << "Failed to connect to database";
        return;
    }

    QSqlQuery query;
    query.prepare(sql);

    if (query.exec()) {
        while (query.next()) {
            QJsonObject jsonData;
            jsonData["RecordID"] = query.value(0).toInt();
            jsonData["PatientID"] = query.value(1).toInt();
            jsonData["DoctorID"] = query.value(2).toInt();
            jsonData["Diagnosis"] = query.value(3).toString();
            jsonData["Treatment"] = query.value(4).toString();
            jsonData["Date"] = query.value(5).toString();
            jsonArray.append(jsonData);
        }

        QJsonDocument jsonDoc(jsonArray);
        jsonString = jsonDoc.toJson();
        qDebug() << "Sending JSON:" << jsonString;
        sendMsg(jsonString);
    } else {
        qDebug() << "Query execution failed:" << query.lastError().text();
    }
}

// 处理预约请求
void ServerTcp::onReadMsg_ReturnAppointments() {
    QByteArray data = socket->readAll();
    sql = QString::fromUtf8(data);
    qDebug() << "Received data:" << data;
    sendAppointmentsData(); // 发送预约数据
}

void ServerTcp::onReadMsg_ReturnAppointments_2() {
    QByteArray data = socket->readAll();
    sql = QString::fromUtf8(data);
    qDebug() << "Received data:" << data;
    sendAppointmentsData_2(); // 发送预约数据
}

// 发送预约数据
void ServerTcp::sendAppointmentsData() {

    jsonArray = QJsonArray();
    sql = sql.trimmed();
    qDebug() << "Executing SQL:" << sql;

    DatabaseHandler db;
    if (!db.connectToDatabase(DATABASE_PATH)) {
        qDebug() << "Failed to connect to database";
        return;
    }

    QSqlQuery query;
    query.prepare(sql);

    if (query.exec()) {
        while (query.next()) {
            QJsonObject jsonData;
            jsonData["AppointmentID"] = query.value(0).toString();         // 预约ID
            jsonData["AppointmentDate"] = query.value(1).toString();             // 病人ID
            jsonData["Status"] = query.value(2).toString();              // 医生ID
            jsonData["DoctorID"] = query.value(3).toString();    // 预约日期
            jsonData["DoctorName"] = query.value(4).toString();             // 预约状态
            jsonData["Department"] = query.value(5).toString();         // 医生所属部门

            jsonArray.append(jsonData);
        }
        QJsonDocument jsonDoc(jsonArray);
        jsonString = jsonDoc.toJson();
        qDebug() << "Sending JSON:" << jsonString;
        sendMsg(jsonString);
    } else {
        qDebug() << "Query execution failed:" << query.lastError().text();
    }
}

// 发送预约数据
void ServerTcp::sendAppointmentsData_2() {

    jsonArray = QJsonArray();
    sql = sql.trimmed();
    qDebug() << "Executing SQL:" << sql;

    DatabaseHandler db;
    if (!db.connectToDatabase(DATABASE_PATH)) {
        qDebug() << "Failed to connect to database";
        return;
    }

    QSqlQuery query;
    query.prepare(sql);

    if (query.exec()) {
        while (query.next()) {
            QJsonObject jsonData;
           jsonData["AppointmentID"] = query.value(0).toInt();
            jsonData["PatientID"] = query.value(1).toInt();
            jsonData["DoctorID"] = query.value(2).toInt();
            jsonData["AppointmentDate"] = query.value(3).toString();
            jsonData["Status"] = query.value(4).toString();
            jsonData["PatientName"] = query.value(5).toString(); // 获取患者名


            jsonArray.append(jsonData);
        }

        QJsonDocument jsonDoc(jsonArray);
        jsonString = jsonDoc.toJson();
        qDebug() << "Sending JSON:" << jsonString;
        sendMsg(jsonString);
    } else {
        qDebug() << "Query execution failed:" << query.lastError().text();
    }
}

// 处理医疗建议请求
void ServerTcp::onReadMsg_ReturnMedicalAdvice() {
    QByteArray data = socket->readAll();
    sql = QString::fromUtf8(data);
    qDebug() << "Received data:" << data;
    sendMedicalAdviceData(); // 发送医疗建议数据
}

// 发送医疗建议数据
void ServerTcp::sendMedicalAdviceData() {
    jsonArray = QJsonArray();
    sql = sql.trimmed();
    qDebug() << "Executing SQL:" << sql;

    DatabaseHandler db;
    if (!db.connectToDatabase(DATABASE_PATH)) {
        qDebug() << "Failed to connect to database";
        return;
    }

    QSqlQuery query;
    query.prepare(sql);

    if (query.exec()) {
        while (query.next()) {
            QJsonObject jsonData;
            jsonData["AdviceID"] = query.value(0).toInt();
            jsonData["PatientID"] = query.value(1).toInt();
            jsonData["DoctorID"] = query.value(2).toInt();
            jsonData["Advice"] = query.value(3).toString();
            jsonData["Date"]  = query.value(4).toString();
            jsonArray.append(jsonData);
        }

        QJsonDocument jsonDoc(jsonArray);
        jsonString = jsonDoc.toJson();
        qDebug() << "Sending JSON:" << jsonString;
        sendMsg(jsonString);
    } else {
        qDebug() << "Query execution failed:" << query.lastError().text();
    }
}

// 处理处方请求
void ServerTcp::onReadMsg_ReturnPrescriptions() {
    QByteArray data = socket->readAll();
    sql = QString::fromUtf8(data);
    qDebug() << "Received data:" << data;
    sendPrescriptionsData(); // 发送处方数据
}

// 发送处方数据
void ServerTcp::sendPrescriptionsData() {
    jsonArray = QJsonArray();
    sql = sql.trimmed();
    qDebug() << "Executing SQL:" << sql;

    DatabaseHandler db;
    if (!db.connectToDatabase(DATABASE_PATH)) {
        qDebug() << "Failed to connect to database";
        return;
    }

    QSqlQuery query;
    query.prepare(sql);

    if (query.exec()) {
        while (query.next()) {
            QJsonObject jsonData;
            jsonData["PrescriptionID"] = query.value(0).toInt();
            jsonData["PatientID"] = query.value(1).toInt();
            jsonData["DoctorID"] = query.value(2).toInt();
            jsonData["Medication"] = query.value(3).toString();
            jsonData["Dosage"] = query.value(4).toString();
            jsonData["Date"] = query.value(5).toString();
            jsonArray.append(jsonData);
        }

        QJsonDocument jsonDoc(jsonArray);
        jsonString = jsonDoc.toJson();
        qDebug() << "Sending JSON:" << jsonString;
        sendMsg(jsonString);
    } else {
        qDebug() << "Query execution failed:" << query.lastError().text();
    }
}

// 处理通信数据请求
void ServerTcp::onReadMsg_ReturnCommunication() {
    QByteArray data = socket->readAll();
    sql = QString::fromUtf8(data);
    qDebug() << "Received data:" << data;
    sendCommunicationData(); // 发送通信数据
}

// 发送通信数据
void ServerTcp::sendCommunicationData() {
    jsonArray = QJsonArray();
    sql = sql.trimmed();
    qDebug() << "Executing SQL:" << sql;

    DatabaseHandler db;
    if (!db.connectToDatabase(DATABASE_PATH)) {
        qDebug() << "Failed to connect to database";
        return;
    }

    QSqlQuery query;
    query.prepare(sql);

    if (query.exec()) {
        while (query.next()) {
            QJsonObject jsonData;
            jsonData["MessageID"] = query.value(0).toInt();
            jsonData["PatientID"] = query.value(1).toInt();
            jsonData["DoctorID"] = query.value(2).toInt();
            jsonData["Message"] = query.value(3).toString();
            jsonData["Date"] = query.value(4).toString();
            jsonArray.append(jsonData);
        }

        QJsonDocument jsonDoc(jsonArray);
        jsonString = jsonDoc.toJson();
        qDebug() << "Sending JSON:" << jsonString;
        sendMsg(jsonString);
    } else {
        qDebug() << "Query execution failed:" << query.lastError().text();
    }
}

// 处理健康评估请求
void ServerTcp::onReadMsg_ReturnHealthAssessments() {
    QByteArray data = socket->readAll();
    sql = QString::fromUtf8(data);
    qDebug() << "Received data:" << data;
    sendHealthAssessmentsData(); // 发送健康评估数据
}

// 发送健康评估数据
void ServerTcp::sendHealthAssessmentsData() {
    jsonArray = QJsonArray();
    sql = sql.trimmed();
    qDebug() << "Executing SQL:" << sql;

    DatabaseHandler db;
    if (!db.connectToDatabase(DATABASE_PATH)) {
        qDebug() << "Failed to connect to database";
        return;
    }

    QSqlQuery query;
    query.prepare(sql);

    if (query.exec()) {
        while (query.next()) {
            QJsonObject jsonData;
            jsonData["AssessmentID"] = query.value(0).toInt();
            jsonData["PatientID"] = query.value(1).toInt();
            jsonData["Assessment"] = query.value(2).toString();
            jsonData["Date"] = query.value(3).toString(); // 添加日期字段

            jsonArray.append(jsonData);
        }

        QJsonDocument jsonDoc(jsonArray);
        jsonString = jsonDoc.toJson();
        qDebug() << "Sending JSON:" << jsonString;
        sendMsg(jsonString);
    } else {
        qDebug() << "Query execution failed:" << query.lastError().text();
    }
}
